import {
	Component
} from 'react';
import {
	Tab,
	Button,
	TextareaField,
	ScrollList,
	Group,
	Boxs,
	Avatar,
	Badge,
	ActionSheet,
	Dialog,
	Toast,
	Grid,
	ImageViewer,
} from 'saltui';
const {
	IconButton
} = Button;
const {
	HBox,
	Box
} = Boxs;

import {
	urlPrefix,
	URLS,
	nodataIcon,
	dictMap
} from '../../app/variables';
import DB from '../../app/db';
let ActionSheetButton;
export default class PostInfo extends Component {
	constructor(props) {
		super(props);
		var context = document.getElementById("context").value;
		this.state = {
			post: props.postView,
			isAuthor:props.isAuthor,
			pagetype:props.pagetype,
			postId : props.postId,
			urlPrev: context + '/api/m/plugin/attachment/mobile/viewImage?fid=',
		}
		
		this.OPERATE = [
		{
			name: '编辑',
			code: 'edit'
		},
		{
			name: '置顶',
			code: 'top',                        
		},
		{
			name: '取消置顶',
			code: 'untop'
		},
		{
			name: '设置精华',
			code: 'essence',                        
		},
		{
			name: '取消精华',
			code: 'unEssence'
		},
		{
			name: '标签',
			code: 'label'
		},
		{
			name: '移动',
			code: 'move'
		},
		{
			name: '删除',
			code: 'delete'
		}
		];
		
	}
	componentWillMount() {
		this.judgeOperate();
	}

	componentWillUnmount(){
		if(ActionSheetButton){
	      ActionSheetButton.close();
	    }
	}

	judgeOperate() {
		let option = this.generateIndependentOptions();
		var isAuthor=this.state.post.isAuthor;
		var isModerator=this.state.post.isModerator;
		var checkStatus=this.state.post.checkStatus;
		var boardIsDelete=this.state.post.boardIsDelete;
		var boardStatus=this.state.post.boardStatus;		
		//alert("isModerator:" + isModerator + ";isAuthor:" + isAuthor + ";checkStatus:" + checkStatus);
		// 根据每一项的信息判断是否显示options
		// 所有列表页面
		if(this.state.pagetype == 'mypost'){
			if(checkStatus == '2'||checkStatus== '4'||checkStatus== '3'){
				//1.版块不被禁用的可以进入if2.版块被禁用但帖子是审核不通过的可以进入if
				if(boardStatus == '1' || (boardStatus == '2'&& checkStatus== '3')){
					//是否是版主,管理员,作者
					if (isModerator||this.state.post.isAdminRole||this.state.post.canSendPost=='1') {
						if(this.state.post.isEditPost=='1'){
							this.pushInIndependentOptions(option, 'edit');
						}
					}else{
						if(this.state.post.countSend==null){
							this.pushInIndependentOptions(option, 'edit');
						}
					}
				}
				    this.pushInIndependentOptions(option, 'delete');
			}
		}else if(this.state.pagetype == 'board'){
			//是否置顶
			if(this.state.post.isTop== '1'){
				//是否是精华
				if(this.state.post.isEssence == '1'){
					if(this.state.post.isAdminRole){
						this.pushInIndependentOptions(option, 'edit');
						this.pushInIndependentOptions(option, 'untop');
						this.pushInIndependentOptions(option, 'unEssence');
						this.pushInIndependentOptions(option, 'label');
						this.pushInIndependentOptions(option, 'move');
						this.pushInIndependentOptions(option, 'delete');
					}else if(isModerator){
						this.pushInIndependentOptions(option, 'untop');
						this.pushInIndependentOptions(option, 'unEssence');
						this.pushInIndependentOptions(option, 'label');
						this.pushInIndependentOptions(option, 'delete');
					}else if(isAuthor){
						if(this.state.post.isEditPost=='1'){
							this.pushInIndependentOptions(option, 'edit');
						}
						this.pushInIndependentOptions(option, 'delete');
					}
				}else{
					if(this.state.post.isAdminRole){
						this.pushInIndependentOptions(option, 'edit');
						this.pushInIndependentOptions(option, 'untop');
						this.pushInIndependentOptions(option, 'essence');
						this.pushInIndependentOptions(option, 'label');
						this.pushInIndependentOptions(option, 'move');
						this.pushInIndependentOptions(option, 'delete');
					}else if(isModerator){
						this.pushInIndependentOptions(option, 'untop');
						this.pushInIndependentOptions(option, 'essence');
						this.pushInIndependentOptions(option, 'label');
						this.pushInIndependentOptions(option, 'delete');
					}else if(isAuthor){
						if(this.state.post.isEditPost=='1'){
							this.pushInIndependentOptions(option, 'edit');
						}
						this.pushInIndependentOptions(option, 'delete');
					}
				}
				
			}else{
				if(this.state.post.isEssence == '1'){
					if(this.state.post.isAdminRole){
						this.pushInIndependentOptions(option, 'edit');
						this.pushInIndependentOptions(option, 'top');
						this.pushInIndependentOptions(option, 'unEssence');
						this.pushInIndependentOptions(option, 'label');
						this.pushInIndependentOptions(option, 'move');
						this.pushInIndependentOptions(option, 'delete');
					}else if(isModerator){
						this.pushInIndependentOptions(option, 'top');
						this.pushInIndependentOptions(option, 'unEssence');
						this.pushInIndependentOptions(option, 'label');
						this.pushInIndependentOptions(option, 'delete');
					}else if(isAuthor){
						if(this.state.post.isEditPost=='1'){
							this.pushInIndependentOptions(option, 'edit');
						}
						this.pushInIndependentOptions(option, 'delete');
					}
				}else{
					if(this.state.post.isAdminRole){
						this.pushInIndependentOptions(option, 'edit');
						this.pushInIndependentOptions(option, 'top');
						this.pushInIndependentOptions(option, 'essence');
						this.pushInIndependentOptions(option, 'label');
						this.pushInIndependentOptions(option, 'move');
						this.pushInIndependentOptions(option, 'delete');
					}else if(isModerator){
						this.pushInIndependentOptions(option, 'edit');
						this.pushInIndependentOptions(option, 'top');
						this.pushInIndependentOptions(option, 'essence');
						this.pushInIndependentOptions(option, 'label');
						this.pushInIndependentOptions(option, 'delete');
					}else if(isAuthor){
						if(this.state.post.isEditPost=='1'){
							this.pushInIndependentOptions(option, 'edit');
						}
						this.pushInIndependentOptions(option, 'delete');
					}
				}
				
			}
		}
		this.setState({
			option: option
		});
	}
/**
	 * 生成独立操作空间(数组)
	 * @return {[type]}
	 */
	generateIndependentOptions() {
		return new Array();
	}

	
	/**
	 * 获取操作改变
	 * @param  {[type]}
	 * @return {[type]}
	 */
	acquireOptionWithName(n) {
		let s;
		this.OPERATE.map((item, index) => {
			if (item.code == n) {
				s = item;
				return item;
			}
		});
		return s;
	}

	/**
	 * 获取独立空间中操作选项的名称
	 * @param  {[type]}
	 * @return {[type]}
	 */
	acquireIndependentOptionsName(options) {
		let names = [];
		if (options && options.length > 0) {
			options.map((item, index) => {
				names.push(item.name);
			});
		}
		return names;
	}

	/**
	 * 根据code获取操作放入独立空间
	 * 
	 * @param  {[type]}
	 * @param  {[type]}
	 * @return {[type]}
	 */
	pushInIndependentOptions(options, code) {
		if (options instanceof Array) {
			let n = this.acquireOptionWithName(code);
			options.push(n);
		}
		return options;
	}
	/**
	 * 帖子操作按钮的点击触发事件
	 *  所有帖子: 版主+管理员+本人 -- 编辑删除; 一般用户: 查看
	 *  我的发帖: 一般用户: 
	 * @return {[type]}
	 */
	handleOperateClick(e) {
		let t = this;
		let length = t.state.option.length;
		ActionSheetButton = ActionSheet.show({
			options: t.acquireIndependentOptionsName(t.state.option),
			destructiveButtonIndex: length-1,
			maskClosable: true,
		},
		t.clickOperateItem.bind(t, t.state.option));
	}

	checkButtonClick(){
		this.showConfirm('check', '确定审核通过吗？', {
			id: this.state.postId
		});
	} 

	editButtonClick(){
		location.hash = 'post/edit/' + this.state.postId + '/' + this.state.post.checkStatus + '/' + this.state.post.author+'/'+this.state.pagetype;
	} 

	deleteButtonClick(){
		this.showConfirm('delete', '确定删除该记录吗？', {
			id: this.state.postId
		});
	} 

	cancelButtonClick(){
		history.back();
	}

	confirmDialogButton(optionCode, argParam) {
		if (optionCode == 'delete') {
			let param = {
				ids: argParam.id,
				pagetype: this.state.pagetype
			};
			DB.ForumModuleAPI.deletePost(param).then((content) => {
				Toast.show({
					type: 'success',
					content: '删除成功',
				});
				//window.salt.router.goBack();
				history.back();
			}).catch((error) => {
				Toast.show({
					type: 'error',
					content: error.errorMsg,
				});
			});
		}
		else if (optionCode == 'check') {
			let param = {
				ids: argParam.id
			};
			DB.ForumModuleAPI.checkPost(param).then((content) => {
				Toast.show({
					type: 'success',
					content: '审核成功',
				});
				window.salt.router.goBack();
			}).catch((error) => {
				Toast.show({
					type: 'error',
					content: error.errorMsg,
				});
			});
		} else if (optionCode == 'top' ) {
			let param = {
				id: argParam.id
			};
			DB.ForumModuleAPI.topPost(param).then((content) => {
				Toast.show({
				type: 'success',
				content: '置顶成功',
				});
				//this.props.flushData();
				history.go(-1);
			}).catch((error) => {
				Toast.show({
					type: 'error',
					content: error.errorMsg,
				});
			});
		}else if(optionCode == 'untop'){
			let param = {
				id: argParam.id
			};
			DB.ForumModuleAPI.topPost(param).then((content) => {
				Toast.show({
					type: 'success',
					content: '取消置顶成功',
				});
				history.go(-1);
			}).catch((error) => {
				Toast.show({
					type: 'error',
					content: error.errorMsg,
				});
			});
		}else if(optionCode == 'essence'){
			let param = {
				id: argParam.id
			};
			DB.ForumModuleAPI.essencePost(param).then((content) => {
				Toast.show({
					type: 'success',
					content: '设置精华成功',
				});
				history.go(-1);
			}).catch((error) => {
				Toast.show({
					type: 'error',
					content: error.errorMsg,
				});
			});
		}else if(optionCode == 'unEssence'){
			let param = {
				id: argParam.id
			};
			DB.ForumModuleAPI.essencePost(param).then((content) => {
				Toast.show({
					type: 'success',
					content: '取消精华成功',
				});
				history.go(-1);
			}).catch((error) => {
				Toast.show({
					type: 'error',
					content: error.errorMsg,
				});
			});
		}
	}

	/**
	 * 单独处理审核帖子页面不通过操作
	 */
	unPass(){
		let id = this.state.postId;
		let route = "myCheckView";
		location.hash = 'post/unCheck/' + id +'/' +route;
	}

	/**
	 * 单独处理审核帖子页面通过操作
	 */
	pass(){
		let id = this.state.postId;
		Dialog.confirm({
			title: '提示',
		   // locale: 'en_US',
		   content: "确定审核通过吗?",
		   onConfirm: this.returnCheck.bind(this,id),
		   onCancel: (var1) => {
			   console.log('confirm cancel');
		   },
	   });
	}

	returnCheck(ids){
		DB.ForumModuleAPI.returnPost({
			id:this.state.postId,
		}).then((content) =>{
			Dialog.alert({
				title: '提交',
				content: '审核成功',
			});
			backPage();
		}).catch((error) => {
			Toast.show({
				type: 'error',
				content: '提交出错'
			});
		})
	}

	/**
	 * 对每一个帖子的操作面板按钮的点击触发事件
	 * @param  {[type]}
	 * @param  {[type]}
	 * @return {[type]}
	 */
	clickOperateItem(option, index) {
		var postId=this.state.postId;
		if (index == -1) {
			return;
		}
		let opt = option[index];
		 if (opt.code == 'delete') {
			this.showConfirm(opt.code, '确定删除该记录吗？', {
				id: postId
			});
		}else if(opt.code == 'label'){
			if (this.state.post.type == 1) {
				// 主题帖
				location.hash = 'post/label/' + postId;
			}
		} else if(opt.code == 'move'){
			location.hash = 'post/move/' +postId + '/' + this.state.post.boardId;
		}
		else if (opt.code == 'edit') {
			if(this.state.isAuthor){
				location.hash = 'post/edit/' + postId + '/' + this.state.post.checkStatus + '/' + this.state.post.author+'/'+this.state.pagetype + '/' + this.state.isAuthor;
			}else{
				location.hash = 'post/unEdit/' + postId + '/' + this.state.post.checkStatus + '/' + this.state.post.author+'/'+this.state.pagetype + '/' + this.state.isAuthor;
			}
		} else if (opt.code == 'check') {
			this.showConfirm(opt.code, '确定审核通过吗？', {
				id: postId
			});
		}else if (opt.code == 'reply') {
			this.handleQuickReply();
		}else if (opt.code == 'quote') {
			location.hash = 'post/reply/' + this.state.post.isShowAnonymity + '/' + postId + '/' + this.state.post.boardId + '/undefined/' + this.state.post.id + '/' + this.state.post.author + '/' + this.state.post.checkStatus;
		}if (opt.code == 'top') {
			this.showConfirm(opt.code, '确定' + opt.name+'该帖子吗？', {
				id: postId
			});
		}if (opt.code == 'untop') {
			this.showConfirm(opt.code, '确定' + opt.name+'该帖子吗？', {
				id: postId
			});
		}if (opt.code == 'essence') {
			this.confirmDialogButton(opt.code,{id: postId})
			// this.showConfirm(opt.code, '确定' + opt.name+'吗？', {
			// 	id: postId
			// });
		}if (opt.code == 'unEssence') {
			this.confirmDialogButton(opt.code,{id: postId})
			// this.showConfirm(opt.code, '确定' + opt.name+'吗？', {
			// 	id: postId
			// });
		}
	}

/**
	 * 操作面板点击后页面显示操作确认框
	 * @param  {[type]}
	 * @param  {[type]}
	 * @param  {[type]}
	 * @return {[type]}
	 */
	showConfirm(optionCode, content, param) {

		Dialog.confirm({
			title: '提示',
			content: content,
			onConfirm: this.confirmDialogButton.bind(this, optionCode, param),
			onCancel: (var1) => {
				console.log('confirm cancel');
			},
		});
	}




	render() {
		var pagetype = this.state.pagetype;
		var rejection = this.state.post.rejection;
		var checkStatus = this.state.post.checkStatus;
		var token = document.getElementById("token").value;
		var isNormalPeople;
		if((this.state.post.isAdminRole==false && this.state.post.isAuthor==false && this.state.post.isModerator==false)||(checkStatus=="1")){
			isNormalPeople =true;
		}else{
			isNormalPeople =false;
		}
		var url=this.state.urlPrev;
		let t = this;
		var isTop=this.state.post.isTop;
		var publishTime = '';
		if(this.state.post.publishTime != undefined&&this.state.post.publishTime!='undefined'){
			publishTime = this.state.post.publishTime;
		}
		var picUrl = "";
		var dingUrl = "";
		let labels_html;
		if (this.state.post.labels && this.state.post.labels.length > 0) {
			labels_html = this.state.post.labels.map((item, index) => {
				var labelColor = "t-tag-"+item.color+" t-MR4";
				var labelName = item.name;
				return (<span className={labelColor}>{labelName}</span>);
			});
		}
		var photosize = 0;
		var photo_html;
		var imgId;
		if (this.state.post.attIdJson!=null && this.state.post.attIdJson.length > 0) {	
			photo_html = this.state.post.attIdJson.map((item, index) => {
				picUrl = url + item.id+'&token='+token;
				dingUrl = JSON.stringify(picUrl);
				imgId = item.id;
				photosize++;
				if(index == this.state.post.attIdJson.length-1){
					return(
						<Box>
							<img className="t-R4 " src={picUrl} style={{ width: "100%",objectFit:'cover'}}  />
						</Box>
					);
				}else{
					return(
						<Box>
							<img className="t-R4 t-MB8" src={picUrl} style={{ width: "100%",objectFit:'cover'}}  />
						</Box>
					);
				}
			});
		}

		var imgUrl = '';
		if(this.state.post.image != null&&this.state.post.image != ''){
			imgUrl = url + this.state.post.image+'&token='+token;
		}

		let authorName = this.state.post.authorName;
		if(this.state.post.isAnonymity == 1 && authorName != '匿名' && authorName != null && authorName != 'undefined' && authorName != ''){
			authorName = authorName.substring(0, authorName.indexOf('<'));
		}

		var isModerator=this.state.post.isModerator;
		let checkButton = 0;
		let deleteButton = 0;
		if(isModerator){
			checkButton = 1; deleteButton = 1;
		}
		return (
			<div className="t-BCf">
					<Box className="t-BCf t-PL16 t-PR16 t-PB28">
			            <Box className="t-FS16 t-PT16 t-LH1_4 ">{this.state.post.title}</Box>
			            <HBox vAlign="center" className="t-FCddfontblue-40  t-FS12">
			              	<Box flex={1} className="t-FS14 t-PT6 t-FCddfontblue-60">
								{this.state.post.boardName}
							</Box>
							<HBox vAlign="center" className="t-PT12 t-PR10">
								<Box className="iconfont icon-messages t-FS14 t-MR4"></Box>
								<Box className="t-MR14 t-FS14">{this.state.post.replyCount == null ? '0' : this.state.post.replyCount}</Box>
								<Box className="iconfont icon-eye t-FS14 t-MR4"></Box>
								<Box className="t-FS14">{this.state.post.viewCount == null ? '0' : this.state.post.viewCount}</Box>
                            </HBox>
						</HBox> 	
						<Box className="t-MT8 t-MB20">
						{/* {
							isTop==1?<span className="t-tag-red t-MR4">置顶</span>:''
						} */}
						    {labels_html}
						</Box>
						<Box className="t-PR10 t-FL" style={{marginTop:'-6px'}}>{
				          	(imgUrl!=null&&imgUrl!='')?<Avatar src={imgUrl}/>:<Avatar name={this.state.post.authorName} size={28}/>
				        }
				        </Box>				        
			            <Box className="t-FC3">{this.state.post.authorName}
			            {
			            	(this.state.pagetype=='mypost'&&this.state.post.isAuthor)&&this.state.post.checkStatus!='1'||this.state.pagetype=='board'?
			            	<span onClick={this.handleOperateClick.bind(this)} style={{position: 'absolute',right: '10px'}}>
									<i className={isNormalPeople? "t-DN":"iconfont icon-more t-FCc t-rotate-0"}></i>
							</span>
							:
							""
			            }			            	
						</Box>
			            <Box className="t-MT6 t-FCddfontblue-40 t-FS12 t-MB4">{publishTime}</Box>
			       		<div style={{clear:"both"}}></div>
			            <Box className="t-FS16  t-LH1_6 t-MB20 t-ML4 t-MT10" style={{overflow:"auto"}}>
			            <div dangerouslySetInnerHTML={{__html: this.state.post.content.replace(/(\r\n)|(\n)/g,'</br>').replace(/(\\r\\n)|(\\n)/g,'</br>')}}></div></Box>
						{photo_html}
						<div className={this.state.post.checkStatus=="3"?"":"t-DN"}>
						<TextareaField	           
							required
							label="驳回理由"
							readOnly={true}
							layout="v"
							minRows={8} maxRows={11}
							value={this.state.post.rejection}>/>
						</TextareaField>
						</div>	
		          </Box>
		          <div className="t-H10 t-BCf7"></div>
				  <div className={(pagetype=="myCheck"&&checkStatus=="1")?"dd-bottom-fixed t-P0":"t-DN "}>
							<Button.Group >					
							<Button type="primary" display="banner" onClick={this.pass.bind(this)}>通过</Button>
							<Button type="secondary" display="banner"  onClick={this.unPass.bind(this)} >不通过</Button>	  
							</Button.Group>
					</div>
		        </div>
		);
	}
}